package com.bjsxt.shop.goods.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bjsxt.shop.common.service.impl.BaseServiceImpl;
import com.bjsxt.shop.common.util.ConstatFinalUtil;
import com.bjsxt.shop.common.util.PageInfoUtil;
import com.bjsxt.shop.goods.dao.IAGoodsBrandDao;
import com.bjsxt.shop.goods.dao.IAGoodsCateDao;
import com.bjsxt.shop.goods.pojo.AGoodsBrand;
import com.bjsxt.shop.goods.pojo.AGoodsCate;
import com.bjsxt.shop.goods.service.IGoodsService;

/**
 * 用户相关的Service实现类
 * @author haihai
 *
 */
@Service("goodsService")
public class GoodsServiceImpl extends BaseServiceImpl implements IGoodsService
{
	@Resource
	private IAGoodsBrandDao goodsBrandDao;
	@Resource
	private IAGoodsCateDao  goodsCateDao;
	@Override
	public AGoodsBrand findOneGoodsBrandService(Map<String, Object> condMap)
	{
		return this.goodsBrandDao.findOne(condMap);
	}

	@Override
	public JSONObject saveOneGoodsBrandService(AGoodsBrand goodsBrand)
	{
		JSONObject resultJSON = new JSONObject();
		/* 影响条数 */
		int res = this.goodsBrandDao.save(goodsBrand);
		if(res > 0 )
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			
			/* 存储data */
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("id", goodsBrand.getId() + "");
			dataJSON.put("effect", res + "");
			
			resultJSON.put("data", dataJSON);
		}else
		{
			resultJSON.put("code", "1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
		}
		return resultJSON;
	}
	@Override
	public JSONObject updateOneGoodsBrandService(AGoodsBrand goodsBrand)
	{
		JSONObject resultJSON = new JSONObject();
		/* 影响条数 */
		int res = this.goodsBrandDao.update(goodsBrand);
		/*String str = null ; 
		str.toString();*/
		if(res > 0 )
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "成功");
			
			/* 存储data */
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("id", goodsBrand.getId() + "");
			dataJSON.put("effect", res + "");
			
			resultJSON.put("data", dataJSON);
		}else
		{
			resultJSON.put("code", "2");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("2"));
		}
		return resultJSON;
	}
	
	@Override
	public JSONObject updateOneGoodsBrandService(AGoodsBrand goodsBrand,Map<String, Object> paramsMap)
	{
		JSONObject resultJSON = this.updateOneGoodsBrandService(goodsBrand);
		if("0".equalsIgnoreCase(resultJSON.getString("code")))
		{
			/* 更新品牌成功 */
			/*
			 * 上传图片:
			路径
			网络路径:http://127.0.0.1:8080/shop_back/uploadfile/brand/2017-02-13/uuid.jpg
			真实路径:d:/project/shop_back/uploadfile/brand/2017-02-13/uuid.jpg
			相对路径:/uploadfile/brand/2017-02-13/uuid.jpg
			 * */
			/* 原始文件的名称 "null" */
			String oriFileName = paramsMap.get("oriFileName") + "";
			InputStream inputStream = (InputStream) paramsMap.get("inputStream");
			
			if(paramsMap.get("oriFileName") != null && !"".equalsIgnoreCase(oriFileName))
			{
				/* 数据库存储的是:老的LOGO相对路径 */
				String oldLogoPath = goodsBrand.getLogoPath() ; 
				File oldFile = new File(ConstatFinalUtil.BUNDLE.getString("file.truePath") + oldLogoPath);
				
				/* 相对路径 */
				String relaPath = ConstatFinalUtil.BUNDLE.getString("file.relaPath");
				relaPath += "/brand/" + this.dateFormatUtil.formatDate(new Date()) + "/" + UUID.randomUUID().toString().replaceAll("-", "") 
						+ oriFileName.substring(oriFileName.lastIndexOf("."), oriFileName.length());
				/* 真实路径 */
				String truePath = ConstatFinalUtil.BUNDLE.getString("file.truePath") + relaPath;
				File tarFile = new File(truePath);
				try
				{
					/* 父目录不存在 */
					if(!tarFile.getParentFile().exists())
					{
						tarFile.getParentFile().mkdirs() ; 
					}
					FileOutputStream fos = new FileOutputStream(tarFile);
					/* 文件拷贝 */
					if(!this.fileUtil.copyFile(inputStream, fos))
					{
						ConstatFinalUtil.LOGGER.error("拷贝文件失败了," ,tarFile);
						
						/* 拷贝文件失败,抛异常 */
						String str = null ; 
						str.toString() ; 
					}else
					{
						goodsBrand.setLogoPath(relaPath);
						JSONObject resDBJSON = this.updateOneGoodsBrandService(goodsBrand);
						if("0".equalsIgnoreCase(resDBJSON.getString("code")))
						{
							/* 拷贝新LOGO成功,删除老的 */
							if(oldFile.exists())
							{
								if(!oldFile.delete())
								{
									ConstatFinalUtil.LOGGER.error("删除品牌老LOGO失败,路径:{}",oldFile); 
								}
							}
						}
					}
				} catch (FileNotFoundException e)
				{
				}
			}
		}
		return resultJSON;
	}

	
	@Override
	public JSONObject saveOneGoodsBrandService(AGoodsBrand goodsBrand,Map<String, Object> paramsMap)
	{
		/* 保存品牌 */
		JSONObject resultJSON = this.saveOneGoodsBrandService(goodsBrand);
		if("0".equalsIgnoreCase(resultJSON.getString("code")))
		{
			/* 保存品牌成功 */
			/*
			 * 上传图片:
			路径
			网络路径:http://127.0.0.1:8080/shop_back/uploadfile/brand/2017-02-13/uuid.jpg
			真实路径:d:/project/shop_back/uploadfile/brand/2017-02-13/uuid.jpg
			相对路径:/uploadfile/brand/2017-02-13/uuid.jpg
			 * */
			/* 原始文件的名称 "null" */
			String oriFileName = paramsMap.get("oriFileName") + "";
			InputStream inputStream = (InputStream) paramsMap.get("inputStream");
			
			if(paramsMap.get("oriFileName") != null && !"".equalsIgnoreCase(oriFileName))
			{
				/* 相对路径 */
				String relaPath = ConstatFinalUtil.BUNDLE.getString("file.relaPath");
				relaPath += "/brand/" + this.dateFormatUtil.formatDate(new Date())+ "/" + UUID.randomUUID().toString().replaceAll("-", "") 
						+ oriFileName.substring(oriFileName.lastIndexOf("."), oriFileName.length());
				/* 真实路径 */
				String truePath = ConstatFinalUtil.BUNDLE.getString("file.truePath") + relaPath;
				File tarFile = new File(truePath);
				try
				{
					/* 父目录不存在 */
					if(!tarFile.getParentFile().exists())
					{
						tarFile.getParentFile().mkdirs() ; 
					}
					FileOutputStream fos = new FileOutputStream(tarFile);
					/* 文件拷贝 */
					if(!this.fileUtil.copyFile(inputStream, fos))
					{
						ConstatFinalUtil.LOGGER.error("拷贝文件失败了," ,tarFile);
						/* 拷贝文件失败,抛异常 */
						String str = null ; 
						str.toString() ; 
					}else
					{
						goodsBrand.setLogoPath(relaPath);
						this.updateOneGoodsBrandService(goodsBrand);
					}
				} catch (FileNotFoundException e)
				{
					ConstatFinalUtil.LOGGER.error(e);
				}
			}
		}
		return resultJSON;
	}
	
	
	@Override
	public JSONObject deleteOneGoodsBrandService(AGoodsBrand goodsBrand)
	{
		JSONObject resultJSON = new JSONObject();
		/* 影响条数 */
		int res = this.goodsBrandDao.delete(goodsBrand);
		if(res > 0 )
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "成功");
			
			/* 存储data */
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("id", goodsBrand.getId() + "");
			dataJSON.put("effect", res + "");
			
			resultJSON.put("data", dataJSON);
		}else
		{
			resultJSON.put("code", "3");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("3"));
		}
		return resultJSON;
	}
	
	@Override
	public List<AGoodsBrand> findCondListGoodsBrandService(PageInfoUtil pageInfoUtil,Map<String, Object> condMap)
	{
		/* 为关键字加上%,实现模糊匹配 */
		if(condMap.get("keyword") != null && !"".equalsIgnoreCase(condMap.get("keyword") + ""))
		{
			condMap.put("keyword", "%" + condMap.get("keyword")  + "%");
		}
		
		if(pageInfoUtil != null)
		{
			/* 分页 */
			/* 查询总记录数 */
			condMap.put("pageCount", "true");
			List<AGoodsBrand> roleList = this.goodsBrandDao.findCondList(condMap);
			/* 取总记录数 */
			if(roleList.size() == 1)
			{
				pageInfoUtil.setTotalRecord(roleList.get(0).getId());
			}
			
			/* 查询数据 */
			condMap.put("pageCount", "false");
			/* limit ? , ? */
			condMap.put("currentRecord", pageInfoUtil.getCurrentRecord());
			condMap.put("pageSize", pageInfoUtil.getPageSize());
			return this.goodsBrandDao.findCondList(condMap);
		}
		/* 不分页查询数据 */
		return this.goodsBrandDao.findCondList(condMap);
	}
//-----------------------------------------------------------------------------
	@Override
	public AGoodsCate findOneGoodsCateService(Map<String, Object> condMap)
	{
		return this.goodsCateDao.findOne(condMap);
	}
	
	@Override
	public JSONObject saveOneGoodsCateService(AGoodsCate goodsCate)
	{
		JSONObject resultJSON = new JSONObject();
		/* 影响条数 */
		int res = this.goodsCateDao.save(goodsCate);
		/*String str = null ; 
		str.toString();*/
		if(res > 0 )
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			
			/* 存储data */
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("id", goodsCate.getId() + "");
			dataJSON.put("effect", res + "");
			
			resultJSON.put("data", dataJSON);
		}else
		{
			resultJSON.put("code", "1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
		}
		return resultJSON;
	}
	
	@Override
	public JSONObject updateOneGoodsCateService(AGoodsCate goodsCate)
	{
		JSONObject resultJSON = new JSONObject();
		/* 影响条数 */
		int res = this.goodsCateDao.update(goodsCate);
		/*String str = null ; 
		str.toString();*/
		if(res > 0 )
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "成功");
			
			/* 存储data */
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("id", goodsCate.getId() + "");
			dataJSON.put("effect", res + "");
			
			resultJSON.put("data", dataJSON);
		}else
		{
			resultJSON.put("code", "2");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("2"));
		}
		return resultJSON;
	}

	@Override
	public JSONObject deleteOneGoodsCateService(AGoodsCate goodsCate)
	{
		JSONObject resultJSON = new JSONObject();
		/* 影响条数 */
		int res = this.goodsCateDao.delete(goodsCate);
		/*String str = null ; 
		str.toString();*/
		if(res > 0 )
		{
			resultJSON.put("code", "0");
			resultJSON.put("info", "成功");
			
			/* 存储data */
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("id", goodsCate.getId() + "");
			dataJSON.put("effect", res + "");
			
			resultJSON.put("data", dataJSON);
		}else
		{
			resultJSON.put("code", "3");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("3"));
		}
		return resultJSON;
	}
	
	@Override
	public List<AGoodsCate> findCondListGoodsCateService(PageInfoUtil pageInfoUtil,Map<String, Object> condMap)
	{
		/* 为关键字加上%,实现模糊匹配 
		 * */
		if(condMap.get("keyword") != null && !"".equalsIgnoreCase(condMap.get("keyword") + ""))
		{
			condMap.put("keyword", "%" + condMap.get("keyword")  + "%");
		}
		
		if(pageInfoUtil != null)
		{
			/* 分页 */
			/* 查询总记录数 */
			condMap.put("pageCount", "true");
			List<AGoodsCate> roleList = this.goodsCateDao.findCondList(condMap);
			/* 取总记录数 */
			if(roleList.size() == 1)
			{
				pageInfoUtil.setTotalRecord(roleList.get(0).getId());
			}
			
			/* 查询数据 */
			condMap.put("pageCount", "false");
			/* limit ? , ? */
			condMap.put("currentRecord", pageInfoUtil.getCurrentRecord());
			condMap.put("pageSize", pageInfoUtil.getPageSize());
			return this.goodsCateDao.findCondList(condMap);
		}
		/* 不分页查询数据 */
		return this.goodsCateDao.findCondList(condMap);
	}
	
	/**
	 * 查询整棵树
	 * [
	{ id:1, pId:0, name:"一级分类", open:true},
	{ id:11, pId:1, name:"二级分类",file=''},
	{ id:111, pId:11, name:"三级分类","file":"http://www.baidu.com"},
	{ id:112, pId:11, name:"三级分类"},
	{ id:113, pId:11, name:"三级分类"},
	{ id:114, pId:11, name:"三级分类"},
	{ id:115, pId:11, name:"三级分类"},
	{ id:12, pId:1, name:"二级分类 1-2"},
	{ id:121, pId:12, name:"三级分类 1-2-1"},
	{ id:122, pId:12, name:"三级分类 1-2-2"},
]
	 *//*
	public JSONArray findTreeGoodsCateService(List<AGoodsCate> goodsCateList,String rootPath)
	{
		JSONArray resultArr = new JSONArray();
		for (Iterator iterator = goodsCateList.iterator(); iterator.hasNext();)
		{
			AGoodsCate goodsCate = (AGoodsCate) iterator.next();
			 拼装数据 
			this.findTreeGoodsCateServiceUtil(resultArr, goodsCate,rootPath,0);
			
		}
		return resultArr ; 
	}
	
	private void findTreeGoodsCateServiceUtil(JSONArray resultArr,AGoodsCate goodsCate,String rootPath,int level)
	{
		if(goodsCate != null)
		{
			StringBuffer sb = new StringBuffer();
			for (int i = 0; i < level; i++)
			{
				sb.append("|-->");
			}
			 |-->|-->|-->国产品牌 
			goodsCate.setTreeName(sb.toString() + goodsCate.getName());
			
			JSONObject goodsCateJSON = new JSONObject();
			goodsCateJSON.put("id", goodsCate.getId() + "");
			goodsCateJSON.put("pId", goodsCate.getParentId() + "");
			goodsCateJSON.put("name", goodsCate.getName() + "");
			goodsCateJSON.put("treeName", goodsCate.getTreeName() + "");
			goodsCateJSON.put("spec", goodsCate.getSpec() + "");
			goodsCateJSON.put("open", "true");
			 只有叶子节点才能点击 
			if(goodsCate.getChildCateList().size() == 0)
			{
				goodsCateJSON.put("file", rootPath + "/back/goods/cateUpdate.htm?cid=" + goodsCate.getId());
				goodsCateJSON.put("isLeaf", "1");
			}else
			{
				goodsCateJSON.put("isLeaf", "0");
			}
			resultArr.add(goodsCateJSON);
			
			 查询子节点 
			if(goodsCate.getChildCateList().size() > 0 )
			{
				for (Iterator iterator = goodsCate.getChildCateList().iterator(); iterator.hasNext();)
				{
					AGoodsCate goodsCateChild = (AGoodsCate) iterator.next();
					this.findTreeGoodsCateServiceUtil(resultArr, goodsCateChild,rootPath, level + 1);
				}
			}
		}
	}*/
	//--------------------------------------------
}


